import { truthy } from '@gnlab/utils'
import { App, Button } from 'antd'
import config from '@/config'
import { ReactComponent as FileIcon } from '@/desktop/assets/file.svg'
import formatAssetUrl from '@/desktop/logics/format-asset-url'
import { breakWord } from '@/desktop/styles'
import { commonS } from './common-styles'
import {
  type BaseProps,
  type CommonProps,
  propsWithDefaults,
  useUpload,
  type UploadedFile,
} from './logics'

type FileProps = BaseProps<UploadedFile | null> & Pick<CommonProps, 'mimeType'>

export function UploadFile(props: FileProps) {
  const { message } = App.useApp()
  const { cdn, tips, sizeLimit, value = null, onChange, mimeType } = propsWithDefaults(props)
  const usedSizeLimit = sizeLimit || config.MAX_FILESIZE
  const [uploading, upload] = useUpload(cdn)
  const inputRef = useRef<HTMLInputElement>(null)

  const inputOnChange = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0] ?? null
      e.target.value = ''

      if (file) {
        const size = file.size
        if (size > 1024 * 1024 * usedSizeLimit) {
          void message.warning(`文件不能大于${usedSizeLimit}M`)
          return
        }

        const uploaded = await upload(file)
        if (uploaded) onChange(uploaded)
      }
    },
    [usedSizeLimit, upload, onChange, message],
  )

  return <div css={commonS.upload}>
    {value && value.url ? (
      <div css={s.file}>
        <aside>
          <div className="name">{value.name}</div>
          <a href={formatAssetUrl(value.url)} download={value.name}>
            下载
          </a>
        </aside>
        <FileIcon />
      </div>
    ) : null}

    <Button loading={uploading} onClick={() => inputRef.current?.click()}>
      {value && value.url ? '重新上传' : '上传文件'}
    </Button>
    <div css={commonS.uploadTips}>{truthy(tips) ? tips : `文件大小不得超过${usedSizeLimit}M`}</div>
    <input type="file" ref={inputRef} accept={mimeType || undefined} onChange={inputOnChange} />
  </div>
}

const s = {
  file: css`
    align-items: center;
    background-color: #fff;
    border-radius: 6px;
    border: 1px solid #f5f5f5;
    display: flex;
    margin-bottom: 12px;
    padding: 12px;
    width: 210px;
    aside {
      ${breakWord};
      flex-shrink: 1;
      flex: 1;
      line-height: 1.2;
      margin-right: 14px;
      .name {
        font-size: 12px;
        margin-bottom: 8px;
        min-height: 1.5em;
      }
    }
    svg {
      width: 52px;
      height: 52px;
    }
    a {
      display: block;
      font-size: 12px;
      transform-origin: left bottom;
      transform: scale(0.83);
    }
  `,
}
